import React from 'react';
import { inject, observer } from 'mobx-react';
import { Row, Col,Button,message,Spin} from 'antd';
import ToolsBar from './ToolsBar';
import Content from './Content';
import loadjs from 'loadjs';

import TagUtil from "../../util/ckextraTagUtil";
import { WeaUpload,WeaTools,WeaLocaleProvider} from "ecCom";

@inject("onlineEditStore")
@observer
class Main extends React.Component {
  static defaultProps = {
    prefixCls: 'wea-odoc-onlineEdit'
  }
  constructor(props) {
    super(props);
    this.state = {
      marginLeft: 0,
      width: 1370, //内容宽度
     
    };
    this.setEditFormHeight = this.setEditFormHeight.bind(this)
  }
  componentDidMount() {
    const {onlineEditStore} = this.props;
    this.onWindowResize();
    window.addEventListener('resize', this.onWindowResize);

    window.saveOnlineEditFile = this.saveFile;
    window.readOnlineEditFile = this.readFile;
    window.changeDisplayAnnotations = onlineEditStore.changeDisplayAnnotations;
    window.notThrowCss = true;
    
  }
  onWindowResize = () => {
    let marginLeft = ( document.body.clientWidth - this.state.width ) / 2;
    if (marginLeft <= 0) marginLeft = 0;
    this.setState({ marginLeft });
    this.setEditFormHeight();
  }

  render() {
    const { prefixCls,onlineEditStore } = this.props;
    const toolsBarHeight = onlineEditStore.showToolBar ? "100px": "17px";
    return (
      <Spin spinning={onlineEditStore.uploading}>
        <div className={`${prefixCls}`}>
          <div className={`${prefixCls}-con`} style={{height:"100%",overflowY: "hidden"}}>
            <ToolsBar />
            <iframe
              src="/spa/odoc/static4Ck/index.html"
               //src="/#"
              width="100%" 
              style={{height:`calc( 100% - ${toolsBarHeight})`}}
              id="CKIframe" 
              name="CKIframe"
              frameborder={0}
              onMouseEnter={()=>onlineEditStore.hiddenPopover()}
            />
          </div>

          <WeaUpload
            uploadUrl='/api/doc/upload/uploadFile'
            category='string'
            maxFilesNumber={1}
            loading={onlineEditStore.loading}
            limitType={'docx'}
            onChange={(ids, list) => this.getlocalFile(ids)}
            style={{display:"none"}}
            onUploading={status=>onlineEditStore.getUploadState(status)}
          >
            <Button  type='primary' id="upLoadFile">选择文件</Button>
          </WeaUpload>
        </div>
      </Spin>
    )
  }

  getlocalFile = (id) => {
    const { onlineEditStore: { setMobxState, setState } } = this.props;
    setMobxState({uploading:true});
    WeaTools.callApi(`/api/odoc/odocFile/convertFileToHtml?imagefileid=${id}`, 'POST').then(data=>{
      setMobxState({uploading:false});
      if(data.result.times == -1){
        message.error(WeaLocaleProvider.getLabel(390468,'转换失败'));
      }else{
        CKIframe.window.ck.set(data.result.htmlStr);
        //fix: 打开本地文件，1.非修订模式，但有痕迹展示；2.显示批注菜单未初始化 (问题： 初始化之后data才加载出来)
        setTimeout(() => {
          // toolbar 初始化
          setState({
            displayAnnotations: false,
            showRevision: false,
          });
          // ck 处于非修订状态
          CKIframe.window.revision(false);
        }, 200);
      }
    })
  }

  //保存文档
  saveFile(){
    var docid;
    const resultStr = jQuery("#CKIframe")[0].contentWindow.submit(true);
    
    var docInfo = parent.parent.WfForm.getOdocConfig();
		jQuery.ajax({
            type: "POST",
            url: "/api/odoc/odocFile/saveFile",
            data: {
              textContent:resultStr,
              docid:docInfo.docParam.docid,
            },
           	cache: false,
           	dataType: 'json',
            async: false,
			      success: function(returndata){
              message.success(WeaLocaleProvider.getLabel(83551,'保存成功！'));
              docid = returndata.docid;
            }
		});
    //保存后，重置撤销列表
    CKIframe.window.CKEditorParams.editorObject.undoManager.reset();
    return docid;
    // WeaTools.callApi(`/api/odoc/odocFile/saveFile?textContent=${resultStr}`, 'POST').then(data=>{
    //     return data.result;
    // })
  }
  //打开文档
  readFile = (docid) => {
    const { onlineEditStore} = this.props;
    WeaTools.callApi(`/api/odoc/odocFile/readFile?docid=${docid}`, 'POST').then(data=>{
      CKIframe.window.ck.set(data.textContent,true);
      let odocConfig = parent.parent.WfForm.getOdocConfig();
      let editFlag = odocConfig.docParam.isEdit === 1;
      if(editFlag){

        // toolbar 初始化
        onlineEditStore.setMobxState({
          showRevision: true,
        });
        window.setTimeout(() => {
            // ck 处于非修订状态
            CKIframe.window.revision(true);
          }, 200);
      }else{

        // toolbar 初始化
        onlineEditStore.setMobxState({
          displayAnnotations: false,
          showRevision: false,
        });
        window.setTimeout(() => {
          // ck 处于非修订状态
          CKIframe.window.revision(false);
          CKIframe.window.CKEditorParams.editorObject.setReadOnly(true)
        }, 200);

      }
    })
  }

  CKIframeRevision = (showRevision,count) => {
    if(count == undefined) count = 0;
    count++;
    try{
        CKIframe.window.revision(showRevision);
    }catch(e){
      if(count <= 20){
        setTimeout(()=>{
          CKIframeRevision(showRevision,count);
        },200)
      }
    }
  }

  setEditFormHeight(){
    const { prefixCls } = this.props;
    jQuery('#CKIframe').height(jQuery('.wea-odoc-onlineEdit-con').height() - 100);
    if(jQuery('#CKIframe')[0].contentWindow.document.getElementById('cke_1_contents')) {
      jQuery('#CKIframe')[0].contentWindow.document.getElementById('cke_1_contents').style.height = (jQuery('#CKIframe').height() - 38) + 'px';
    }
  }
 
}

export default Main
